import {useCallback, useEffect, useState} from "react";
import {setupApp} from "wujie";
import _ from "lodash";

const devMicroUrl = ["//localhost:8081", "//localhost:8082", "//localhost:8083"];
const prodMicroUrl = ["//118.25.141.195:8081", "//118.25.141.195:8082", "//118.25.141.195:8083"];

const URL_MAP = {
    [devMicroUrl[0]]: prodMicroUrl[0],
    [devMicroUrl[1]]: prodMicroUrl[1],
    [devMicroUrl[2]]: prodMicroUrl[2],
};

const hasMicroUrl = url => {
    const dev = process.env.NODE_ENV === "development";
    if (dev) {
        return url;
    }
    return URL_MAP[url];
};

const fetch = url => {
    console.log("fetch", url);
    return window.fetch(url, {credentials: "omit"});
};

const beforeLoad = () => {
    console.log("beforeLoad");
};
const beforeMount = () => {
    console.log("beforeMount");
};
const afterMount = () => {
    console.log("afterMount");
};
const beforeUnmount = () => {
    console.log("beforeUnmount");
};
const afterUnmount = () => {
    console.log("afterUnmount");
};

const admin = {
    url: hasMicroUrl("//localhost:8081"),
    name: "admin",
    props: {a: "b"},
    sync: true,
    fetch,
    beforeLoad,
    beforeMount,
    afterMount,
    beforeUnmount,
    afterUnmount,
};

const h5 = {
    url: hasMicroUrl("//localhost:8082"),
    name: "h5",
    props: {a: "b"},
    sync: true,
    fetch,
    beforeLoad,
    beforeMount,
    afterMount,
    beforeUnmount,
    afterUnmount,
};
const web = {
    url: "//localhost:8083",
    name: "web",
    props: {a: "b"},
    sync: true,
    fetch,
    beforeLoad,
    beforeMount,
    afterMount,
    beforeUnmount,
    afterUnmount,
};

const serverList = [admin, h5, web];

interface MicroProps {
    init?: boolean; // 初始化
    template?: "h5" | "admin" | "web"; // 模板
}

const useMicro = (props: MicroProps) => {
    const {init = false, template} = props;

    const [config, setConfig] = useState(_.find(serverList, {name: template}));

    const handleGetConfig = (name: string = template) => _.find(serverList, {name});
    const handleResetConfig = useCallback((config: any) => {
        setConfig(config);
    }, []);

    const handleCreateMicro = useCallback(props => setupApp(props), []);

    useEffect(() => {
        if (init) {
            serverList.map((item: any) => setupApp(item));
        }
    }, [init]);

    return {config, handleCreateMicro, handleGetConfig, handleResetConfig};
};

export default useMicro;
